package com.hoapital.outpbillwork.billWorkHandler;

import com.hoapital.outpbillwork.module.controller.vo.ApplyInfo;
import com.hoapital.outpbillwork.module.controller.vo.ItemData;
import com.hoapital.outpbillwork.module.controller.vo.OrderInfo;
import com.hoapital.outpbillwork.module.entity.*;
import com.hoapital.outpbillwork.module.mapper.LabTestItemsMapper;
import com.hoapital.outpbillwork.module.mapper.OutpOrderDescTempMapper;
import com.hoapital.outpbillwork.module.service.OutpDoctorAssistantService;
import com.hospital.common.core.constants.AllFinalValueUtils;
import com.hospital.common.core.constants.OrderConstant;
import com.hospital.common.core.exception.ExceptionHelp;
import com.hospital.common.core.exception.ExceptionHelpEnum;
import com.hospital.common.core.hl7Model.hospitalWork.BATCH;
import com.hoapital.outpbillwork.function.setValue.SetFunctionHL7;

import com.hospital.common.core.module.controller.vo.CancelOrder;
import com.hospital.common.core.module.controller.vo.OrderContent;
import com.hospital.common.core.module.controller.vo.Receive;
import com.hoapital.outpbillwork.module.mapper.LabTestMasterMapper;
import com.hospital.common.core.result.SuccessTip;
import com.hospital.common.core.result.Tip;
import com.hospital.common.core.utils.DateUtil;
import com.hospital.common.core.utils.SpringContextHolder;
import com.hospital.common.core.utils.XMLUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lvyao
 * @description 门诊开单检验
 * @date 2022/2/25
 */

@Transactional(rollbackFor = Exception.class)
public class LabOrderBusiness extends AbstractOrderWorkBusiness {


    private LabTestMasterMapper labTestMasterMapper = SpringContextHolder.getBean(LabTestMasterMapper.class);

    private LabTestItemsMapper labTestItemsMapper = SpringContextHolder.getBean(LabTestItemsMapper.class);

    private OutpOrderDescTempMapper outpOrderDescTempMapper = SpringContextHolder.getBean(OutpOrderDescTempMapper.class);

    private OutpDoctorAssistantService outpDoctorAssistantService = SpringContextHolder.getBean(OutpDoctorAssistantService.class);

    @Override
    public ExceptionHelp checkOtherOrder(OrderInfo orderInfo) throws ExceptionHelp {
        return null;
    }

    @Override
    public ExceptionHelp checkOtherExpecOrder(ApplyInfo orderInfo) throws ExceptionHelp {
        String specimen = orderInfo.getOrder().getSpecimen();
        if (StringUtils.isBlank(specimen)) {
            return new ExceptionHelp(ExceptionHelpEnum.NULL_SPECIMEN);
        }
        return null;
    }

    @Override
    public String getOrderNotemp(OrderContent orderContent, Timestamp visitDate, int visitNo) {
        String orderNO = "";
        if (orderContent.getOrderType().equals("C") || orderContent.getOrderType().equals("D")) {
            String testNoDual = labTestMasterMapper.getTestNoDual();
            orderNO = DateUtil.format(visitDate,
                    "yyMMdd") + String.format("%04d", Integer.parseInt(testNoDual));
        }
        return orderNO;
    }


    @Override
    protected LabTestMaster doOtherInfo(List<ItemData> itemDataList, String testNo, PatientInfo patientInfo,
                                        OrderContent order, int age, String testCause, String clininDiag,
                                        Timestamp visitDate, int visitNo,
                                        String subject, int outpId) {
        LabTestMaster labTestMaster = new LabTestMaster();
        labTestMaster.setTestNo(testNo);
        labTestMaster.setPriorityIndicator(0);
        labTestMaster.setPatientId(patientInfo.getPatientId());
        labTestMaster.setName(patientInfo.getName());
        labTestMaster.setNamePhonetic(patientInfo.getNamePhonetic());
        labTestMaster.setChargeType(patientInfo.getChargeType());
        labTestMaster.setSex(patientInfo.getSex());
        labTestMaster.setAge(age);
        labTestMaster.setTestCause(testCause);
        labTestMaster.setRelevantClinicDiag(clininDiag);
        labTestMaster.setSpecimen(order.getSpecimen());
        labTestMaster.setRequestedDateTime(visitDate);
        labTestMaster.setOrderingDept(order.getOrderedByDept());
        labTestMaster.setOrderingProvider(order.getOrderedByDoctor());
        labTestMaster.setPerformedBy(order.getPerformedBy());
        labTestMaster.setResultStatus(AllFinalValueUtils.LAB_RESULT_STATUS);
        labTestMaster.setBillingIndicator(AllFinalValueUtils.CHARGE_FLAG);
        labTestMaster.setSubject(subject);
        labTestMaster.setCosts(new BigDecimal(0));
        labTestMaster.setCharges(new BigDecimal(0));
        labTestMaster.setVisitDate(visitDate);
        labTestMaster.setVisitNo(visitNo);
        labTestMaster.setStatus(AllFinalValueUtils.LAB_MASTER_STATUS);
        labTestMaster.setUserId(AllFinalValueUtils.ALL_OPERATOR);
        labTestMaster.setGreenFlag(AllFinalValueUtils.LAB_MASTER_GREEN_FLAG);
        labTestMaster.setCompanyFlag(order.getCompanyFlag());
        return labTestMaster;
    }

    @Override
    protected LabTestItems doOtherInfoDeatil(String orderNo, int itemNo, String itemCode, String itemName, BigDecimal price, BigDecimal charges) {
        LabTestItems labTestItems = new LabTestItems();
        labTestItems.setTestNo(orderNo);
        labTestItems.setItemNo(itemNo);
        labTestItems.setItemCode(itemCode);
        labTestItems.setItemName(itemName);
        labTestItems.setChargeFlag(AllFinalValueUtils.CHARGE_FLAG);
        labTestItems.setResultStatus(AllFinalValueUtils.LAB_RESULT_STATUS);
        labTestItems.setPrice(charges);
        labTestItems.setCosts(price);
        return labTestItems;
    }

    @Override
    protected BATCH packageMessage(OutpMedrec outpMedrec, List<OutpOrderDescTemp> outpOrderDescTempList, List<Object> labTestMasterList,
                                   List<Object> objectDetail, OrderInfo orderInfo, PatientInfo patientInfo, String orc1, String orc5) {
        return SetFunctionHL7.packageOmallMessage(outpMedrec, outpOrderDescTempList, labTestMasterList,
                objectDetail, orderInfo.getHospitalCode(), orderInfo.getHospitalName(), orderInfo.getOutpOrInp(),
                patientInfo, orc1, orc5, labTestMasterMapper, AllFinalValueUtils.TEST, AllFinalValueUtils.MESSAGE_FROM_LAB
                , AllFinalValueUtils.MESSAGE_EVENT_LAB, AllFinalValueUtils.MESSAGE_EVENT_NAME_LAB);
    }

    @Override
    public Object doOtherBillDetail(String testNo, int outpId, Timestamp visitDate, int visitNo, int itemNo,
                                    ClinicItemBill clinicItemBill, ItemData itemData, OrderContent orderContent, String patientId) {
        return null;
    }

    @Override
    public Object doAfterData(String type, Object object, BigDecimal costs, BigDecimal charges) {
        Object objecdetail = null;
        switch (type) {
            case OrderConstant.ITEM:
                ItemData itemData = (ItemData) object;
                itemData.setCosts(costs);
                itemData.setCharges(charges);
                objecdetail = doOtherInfoDeatil(itemData.getOrderNo(), itemData.getItemNo(), itemData.getItemCode(), itemData.getItemName(), itemData.getCosts(), charges);
                return objecdetail;
            default:
                LabTestMaster labTestMaster = (LabTestMaster) object;
                labTestMaster.setCosts(costs);
                labTestMaster.setCharges(charges);
                return labTestMaster;
        }
    }

    @Override
    public String getReplaceString(BATCH getHl7LabMessage) {

        String utf8 = XMLUtil.convertToXml(getHl7LabMessage).replace(AllFinalValueUtils.MESSAGE_HL7_REPLACE_EXAM_BEF_TARGET, "").
                replace(AllFinalValueUtils.MESSAGE_HL7_REPLACE_EXAM_AFT_TARGET, "").
                replace(AllFinalValueUtils.UNICODE_DEFAULT_TARGET, AllFinalValueUtils.UNICODE_DEFAULT_REPLACEMENT).
                replace("<type>C</type>", "").replace(AllFinalValueUtils.MESSAGE_HL7_REPLACE_LAB_BEF_TARGET, "").
                replace(AllFinalValueUtils.MESSAGE_HL7_REPLACE_LAB_AFT_TARGET, "");
        return utf8;

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateOtherTable(ClinicMaster clinicMaster, OutpMedrec outpMedrec, List<OutpOrderDescTemp> outpOrderDescTempList, List<OutpBillItemsTemp> outpBillItemsTempList,
                                    List<OutpDoctorAssistant> outpDoctorAssistantList,
                                    List<Object> objectMasterList, List<Object> objectItemsList, List<Object> objectBillitemsList,
                                    OutpPrepayRcptTemp outpPrepayRcptTemp, List<OrderVsBillno> orderVsBillnoList) throws ExceptionHelp {

        return outpDoctorAssistantService.updateAllTab(AllFinalValueUtils.TEST, clinicMaster, outpMedrec, outpOrderDescTempList, outpBillItemsTempList, outpDoctorAssistantList, objectMasterList, objectItemsList, objectBillitemsList, outpPrepayRcptTemp, orderVsBillnoList);

    }


    @Override
    public Tip billWork(Receive receive, HttpServletRequest request) throws ExceptionHelp {
        return null;
    }

    @Override
    public Tip orderCancel(CancelOrder CancelOrder, HttpServletRequest request) throws ExceptionHelp {
        return null;
    }

    /**
     * 根据门诊申请检验检查推送申请消息
     *
     * @param oneKey
     * @param msgType
     * @return
     */
    @Override
    public Tip sendApplyHl7File(OrderInfo orderInfo, String oneKey, String msgType) throws ExceptionHelp {
        Map<String, Object> hl7ApplyBaseData = getHl7ApplyBaseData(oneKey, orderInfo.getPatInfo().getPatientId(), orderInfo.getVisitId());
        List<Object> objectMasterList = new ArrayList<>();
        List<Object> objectDetailList = new ArrayList<>();
        List<OutpOrderDescTemp> outpOrderDescTempList = new ArrayList<>();
        for (ApplyInfo applyInfo : orderInfo.getApplyInfo()) {
            objectMasterList.add(labTestMasterMapper.selectById(applyInfo.getOrder().getOrderNo()));
            Map<String, Object> map = new HashMap<>();
            map.put(AllFinalValueUtils.TEST_NO, applyInfo.getOrder().getOrderNo());
            objectDetailList.addAll(labTestItemsMapper.selectByMap(map));

            Map<String, Object> mapOrder = new HashMap<>();
            mapOrder.put(AllFinalValueUtils.OUTP_VISIT_NO, String.valueOf(applyInfo.getOrder().getOrderNoumber()));
            mapOrder.put(AllFinalValueUtils.VISIT_DATE, DateUtil.parseTime(applyInfo.getOrder().getOrderDate()));
            outpOrderDescTempList.addAll(outpOrderDescTempMapper.selectByMap(mapOrder));

            BATCH hl7message = packageMessage((OutpMedrec) hl7ApplyBaseData.get("outpMedrec"), outpOrderDescTempList,
                    objectMasterList, objectDetailList,
                    orderInfo, (PatientInfo) hl7ApplyBaseData.get("patientInfo"), "NW", "SC");
            //xml申请文件保存并推送
            oneKey = DateUtil.formatDate(DateUtil.parseTime(applyInfo.getOrder().getOrderDate()), "yyyyMMddHHmmss") + applyInfo.getOrder().getOrderNoumber();
            boolean push = saveApplyHl7message(orderInfo.getHospitalCode(), orderInfo.getHospitalName(), oneKey, hl7message, msgType);
            if (!push) {
                throw new ExceptionHelp(ExceptionHelpEnum.SEND_APPLY_MSG_FILAD);
            }
            objectMasterList = null;
            objectDetailList = null;
        }
        return new SuccessTip();
    }


}
